<?php

namespace app\common\model;

use function Couchbase\defaultDecoder;
use think\Model;
use think\Validate;
use app\common\controller\Tools;
use think\Db;
use app\common\tool\OSSUtils;

class Goods extends Model
{
    protected $table = 'goods';
    protected $pk = 'goods_id';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'goods_create_time';
    protected $updateTime = 'goods_update_time';

    // 验证规则
    protected $rule = [
        ['goods_merchant_id|商户id', ['require', 'max:30']],
        ['goods_category_id|商品分类', ['require']],
        ['goods_name|商品名称', ['require']],
        ['goods_return_way_id|归还方式', ['require', 'number', '>:0']],
        ['goods_is_real_name|是否需要实名认证', ['require', 'in:1,2']],
    ];

    // 验证场景
    protected $scene = [
        'update' => ['goods_details_name', 'goods_details_content'],
    ];

    // 验证器
    public function intValidate()
    {
        $validate = new \think\Validate($this->rule);
        foreach ($this->scene as $k1 => $v1)
            $validate->scene($k1, $v1);
        return $validate;
    }

    public static function getImgName($imgName)
    {
        $pos = strrpos($imgName, '/');
        $imgName = substr($imgName, $pos);
        return $imgName;
    }

    public static function getGoodsDetails($id)
    {
        $data = [
            'goods_details_merchant_id' => session('merchant.merchant_id'),
            'goods_details_id' => $id
        ];
        $data = db('goods_details')->field('goods_details_content')->where($data)->find();
        return $data;
    }


    // 获取商品类目名称
    public static function getCatName($catId)
    {
        $data = db('goods_category')->field('goods_category_name')->find($catId);
        return $data['goods_category_name'];
    }


    // 租赁规则合约模板
    public static function getLeaseTpl()
    {
        $where = [
            'leasing_rules_merchant_id' => session('merchant.merchant_id'),
            'leasing_rules_is_delete' => 0
        ];
        $data = db('leasing_rules')->field('leasing_rules_id,leasing_rules_name')
            ->where($where)
            ->select();
        return $data;
    }


    // 商品详情模板
    public static function getDetailTpl()
    {
        $where = [
            'goods_details_merchant_id' => session('merchant.merchant_id'),
            'goods_details_is_delete' => 0
        ];
        $data = db('goods_details')->field('goods_details_id,goods_details_name')->where($where)
            ->select();

        return $data;
    }

    // 运费模板
    public static function getFreigtTpl()
    {
        $where = [
            'freight_merchant_id' => session('merchant.merchant_id'),
            'freignt_is_delete' => 0
        ];
        $data = db('freight')->field('freight_id,freight_name,freight_tpl_type')
            ->where($where)
            ->select();

        $result['express_tpl'] = $result['to_door'] = $result['ztd'] = [];
        foreach ($data as $k => $v) {
            if ($v['freight_tpl_type'] == 1) {
                $result['express_tpl'][] = $v;
            }
            if ($v['freight_tpl_type'] == 2) {
                $result['to_door'][] = $v;
            }
        }

        return $result;
    }

    //获取商品信息
    public static function getGoodsId($goods_id)
    {

        $data = db('goods')->where('goods_id', $goods_id)->find();
        return $data;
    }

    // 获取店铺id
    public static function getStoreId()
    {
        $merchantId = session('merchant.merchant_id');
        $store = db('store')->field('store_id')->where('store_merchant_id', $merchantId)->find();

        return $store['store_id'];
    }

    // 获取自提点
    public static function getSinces()
    {
        $where = [
            'since_merchant_id' => session('merchant.merchant_id'),
            'since_is_delete' => 0
        ];
        $data = db('since')->field('since_id,since_tel,since_number,since_detailed_address,since_name')->where($where)->select();

        return $data;
    }


    // 归还地点
    public static function getReturnPlace()
    {
        $where = [
            'revert_merchant_id' => session('merchant.merchant_id'),
            'revert_is_delete' => 0
        ];
        $data = db('revert')->field('revert_id,revent_tel,revent_province,revent_receiver_name,revent_postcode,revert_create_time,revent_detailed_address,revent_city,revent_region')
            ->where($where)
            ->select();

        foreach ($data as $k => &$v) {
            $v['revert_create_time'] = date('Y-m-d H:i:s', $v['revert_create_time']);
        }

        return $data;
    }

    /**
     * 获取商家商品通用配置
     * @return array
     */
    public static function getCommonAttr()
    {
        $merchantId = session('merchant.merchant_id');
        $data = Db('zj_goods_common_attr')
            ->where('merchant_id', intval($merchantId))->order('id desc')->find();
        if ($data) {
            //需要处理的字段 services, rent_period_types, since_sites, return_addrs
            $data['services'] = explode(',', $data['services']);
            $data['rent_period_types'] = json_decode($data['rent_period_types'], TRUE);
            $data['since_sites'] = explode(',', $data['since_sites']);
            $data['return_addrs'] = explode(',', $data['return_addrs']);
        }
        return $data;
    }

    public static function changeDel($goods_id)
    {
        $where = [
            'goods_merchant_id' => session('merchant.merchant_id'),
            'goods_id' => $goods_id
        ];
        $result = Goods::where($where)->setField('goods_is_delete', 1);
        if (!$result)
            return false;

        return true;
    }

    //下架
    public static function putdown($goods_id)
    {
        $where = [
            'goods_merchant_id' => session('merchant.merchant_id'),
            'goods_id' => $goods_id
        ];
        $data = [
            'goods_shelf_state' => 3,
        ];
        $result = Goods::where($where)->setField($data);
        if (!$result)
            return false;

        return true;
    }

    //上架
    public static function puton($goods_id)
    {
        $where = [
            'goods_merchant_id' => session('merchant.merchant_id'),
            'goods_id' => $goods_id
        ];
        $data = [
            'goods_shelf_state' => 2,
            'goods_is_delete' => 0,
            'wap_show' => 0,
            'goods_shelf_time' => time(),
        ];
        $result = Goods::where($where)->setField($data);
        if (!$result)
            return false;

        return true;
    }

    // 插入自提点
    public function insertSince($data)
    {
        $result = db('goods_shipping_tpl')->insert($data);
        if (!$result)
            return false;

        return true;
    }

    // 获取商品
    public function fintgoods($goods_id)
    {
        $result = db('goods')->fint($goods_id);
        return $result;
    }


    //商品
    protected static function init()
    {
        Goods::beforeUpdate(function ($goods) {

            // // 运费模板类型：1-快递模板 2-上门模板 3-自提点'
            $goods_id = input('param.goods_id');
            $since_id = input('param.since_id/a');

            $todoor = input('param.todoor');
            $express_id = input('param.express_id');
            if ($goods_id) {
                if ($since_id)
                    Goods::insertShippingTpls(3, $goods_id, $since_id);
                if ($todoor)
                    Goods::insertShippingTpl(2, $goods_id, $todoor);
                if ($express_id)
                    Goods::insertShippingTpl(1, $goods_id, $express_id);
            }
            // 商品可变属
            $value = input('param.value/a');
            $color = input('param.color/a');
            $guige = input('param.guige/a');
            $market_price = input('param.market_price/a');
            $goods_deposit = input('param.goods_deposit/a');
            // // 可变属性入库
            if ($value) {
                foreach ($value as $k => $v) {
                    foreach ($v as $k1 => $v1) {
                        $data = [
                            'key' => $k,
                            'value' => $v1,
                            'goods_id' => $goods_id
                        ];
                        Db::name('content_var_attr_content')->insert($data);
                    }
                }
            }
            // 商品属性内容(有几个市场价格或者押金就有几个表格,就有几种属性的组合）
            $marketPriceCount = count($market_price);
            $depositCount = count($goods_deposit);
            // 循环颜色规格属性值，获取获取对应id
            $colorId = $guigeId = [];
            $colorCount = count($color);
            $guigeCount = count($guige);
            $rent_period_type = input('param.rent_period_type/a');
            if ($rent_period_type) {
                $rent_period_type = array_filter($rent_period_type);
                $rent_period_type = array_merge($rent_period_type);

            }
            $rentPeriodCount = count($rent_period_type);
            $rent_period_min_rent = input('param.rent_period_min_rent/a');
            $rent_period_max_rent = input('param.rent_period_max_rent/a');
            $rent_period_old_rent_price = input('param.rent_period_old_rent_price/a');
            $rent_period_now_rent_price = input('param.rent_period_now_rent_price/a');
            $rent_period_min_advance = input('param.rent_period_min_advance/a');
            $rent_period_max_advance = input('param.rent_period_max_advance/a');


            // 共有属性入库
            if (isset($color) || isset($guige)) {
                foreach ($goods_deposit as $k => $v) {
                    $colorId[] = self::getVarAttrId($color[$k]);
                    $guigeId[] = self::getVarAttrId($guige[$k]);
                }
                foreach ($market_price as $k => $v) {
                    $agcdata['goods_deposit'] = $goods_deposit[$k];
                    $agcdata['market_price'] = $v;
                    $agcdata['goods_id'] = $goods_id;
                    $currentColor = '';
                    $currentGuige = '';
                    if (isset($colorId[$k])) {
                        $currentColor = $colorId[$k];
                    } else {
                        $currentColor = '';

                    }
                    if (isset($guigeId[$k])) {
                        $currentGuige = $guigeId[$k];
                    } else {
                        $currentGuige = '';
                    }

                    if (($currentColor . $currentGuige) == '') {

                        $agcdata['content_var_attr_id'] = '';
                    } else {
                        $agcdata['content_var_attr_id'] = ($currentColor . ',' . $currentGuige);

                    }
                    $result = Db::name('goods_attr_content')->insert($agcdata);
                }


                // 获取新插入商品的属性name
                $attrIds = Db::name('goods_attr_content')->field('content_var_attr_id')->where('goods_id', $goods_id)->select();
                $_attrIds = [];
                // 获取商品属性id值
                foreach ($attrIds as $k2 => $v2) {
                    $_attrIds[] = $v2['content_var_attr_id'];
                }

                $rent_period_min_rent_count = count($rent_period_min_rent);
                $goods_attr_content_array = db('goods_attr_content')->field('content_id')->where('goods_id', $goods_id)->select();
                $g = count($goods_attr_content_array);
                $j = 0;
                for ($i = 0; $i < $g; $i++) {
                    for ($ii = 0; $ii < $rentPeriodCount; $ii++) {
                        $gugs['content_id'] = $goods_attr_content_array[$i]['content_id'];
                        $gugs['rent_period_type'] = $rent_period_type[$ii];
                        $col_gugs[$j] = $gugs;
                        $j++;
                    }
                }
                for ($i = 0; $i < $rent_period_min_rent_count; $i++) {

                    $data = [
                        'rent_period_type' => $col_gugs[$i]['rent_period_type'],
                        'rent_period_min_rent' => $rent_period_min_rent[$i],
                        'rent_period_max_rent' => ($rent_period_max_rent[$i] == 0 ? (100) : $rent_period_max_rent[$i]),
                        'rent_period_old_rent_price' => $rent_period_old_rent_price[$i],
                        'rent_period_now_rent_price' => $rent_period_now_rent_price[$i],
                        'rent_period_min_advance' => $rent_period_min_advance[$i],
                        'rent_period_max_advance' => $rent_period_max_advance[$i] * 30,
                        'rent_period_goods_id' => $goods_id,
                        'rent_period_goods_attr_id' => $col_gugs[$i]['content_id'],
                        'rent_period_create_time' => time(),
                    ];
                    Db::name('rent_period')->insert($data);
                }
            }

            //select  *  from  content_var_attr_content where goods_id=388
            // 商品sku属性及图片入库
            $goods_sku_img = input('param.goods_sku_img/a');
            $goods_sku_attr_value = input('param.goods_sku_attr_value/a');

            $my_goods_id = input('param.goods_id');

            if ($goods_sku_img) {
                $goods_sku_imgCount = count($goods_sku_img);
                $goods_sku_attr_value = array_filter($goods_sku_attr_value);
                foreach ($goods_sku_img as $k => $v) {
                    $where = [
                        'value' => $goods_sku_attr_value[$k],
                        'goods_id' => $my_goods_id,
                    ];
                    $attrs = db('content_var_attr_content')
                        ->field('content_id')
                        ->where($where)
                        ->find();

                    $data = [
                        'goods_sku_img' => $v,
                        'goods_id' => $my_goods_id,
                        'goods_sku_attr_name' => '',
                        'goods_sku_attr_id' => $attrs['content_id'],
                        'goods_sku_attr_value' => $goods_sku_attr_value[$k]
                    ];

                    Db::name('goods_sku')->insert($data);

                }
            }


            // // // 商品主图入库
            $goodsMain = input('param.goods_main_pic/a');

            if (!empty($goodsMain)) {
                $goodsMainCount = count($goodsMain);
                $goodsMain = array_filter($goodsMain);
                foreach ($goodsMain as $k => $v) {
                    if ($k == 0) {
                        $data = [
                            'goods_main_pic' => $v,
                            'goods_id' => $goods_id,
                            'goods_is_main_pic' => 1
                        ];

                        Db::name('goods_main_img')->insert($data);
                    } else {
                        $data = [
                            'goods_main_pic' => $v,
                            'goods_id' => $goods_id,
                            'goods_is_main_pic' => 2
                        ];
                        Db::name('goods_main_img')->insert($data);
                    }
                }
            }
            // // 商品租赁清单入库
            $rentlist = input('param.goods_rentlist_img/a');
            $rentlist_name = input('param.goods_rentlist_name/a');
            if ($rentlist && $rentlist_name) {
                $rentlistImg = array_filter($rentlist);
                $goods_rentlist_name = array_filter($rentlist_name);
                foreach ($rentlistImg as $k => $v) {

                    $data = [
                        'goods_id' => $goods_id,
                        'goods_rentlist_img' => $v,
                        'goods_rentlist_name' => isset($goods_rentlist_name[$k]) ? $goods_rentlist_name[$k] : '',
                    ];

                    Db::name('goods_rentlist')->insert($data);
                }
            }


        });
    }


    // 获得可变属性的id
    private static function getVarAttrId($attrName)
    {
        if (empty($attrName))
            return $attrId = '';
        $goodsId = input('param.goods_id');
        $where = [
            'value' => $attrName,
            'goods_id' => $goodsId,
        ];
        $attrData = db('content_var_attr_content')
            ->field('content_id')
            ->where($where)
            ->find();
        $attrId = $attrData['content_id'];

        return $attrId;
    }

    private static function getVarAttrIdS($attrName, $goodsId)
    {
        if (empty($attrName))
            return $attrId = '';

        $where = [
            'value' => $attrName,
            'goods_id' => $goodsId,
        ];
        $attrData = db('content_var_attr_content')
            ->field('content_id')
            ->where($where)
            ->find();
        $attrId = $attrData['content_id'];

        return $attrId;
    }

    private static function insertShippingTpl($goods_shipping_tpl_type, $goods_id, $goods_shipping_tpl_selected)
    {
        $data = [
            'goods_shipping_tpl_type' => $goods_shipping_tpl_type,
            'goods_id' => $goods_id,
            'goods_shipping_tpl_selected' => $goods_shipping_tpl_selected,
        ];
        db('goods_shipping_tpl')->insert($data);
    }

    private static function insertShippingTpls($goods_shipping_tpl_type, $goods_id, $goods_shipping_tpl_selected)
    {
        $count = count($goods_shipping_tpl_selected);
        for ($i = 0; $i < $count; $i++) {
            $data = [
                'goods_shipping_tpl_type' => $goods_shipping_tpl_type,
                'goods_id' => $goods_id,
                'goods_shipping_tpl_selected' => $goods_shipping_tpl_selected[$i],
            ];
            db('goods_shipping_tpl')->insert($data);
        }
    }

    public static function showlist($pagesize, $type)
    {
        $where['a.goods_merchant_id'] = ['eq', session('merchant.merchant_id')];
        $where['a.goods_is_delete'] = ['eq', 0];
        $keyword = input('param.keyword', '');
        if ($keyword) {
            $where['a.goods_name'] = ['like', "%$keyword%"];
        }

        $begintime = input('param.begintime', '');
        $endtime = input('param.endtime', '');
        if ($begintime && $endtime)
            $where['a.goods_create_time'] = ['between', [strtotime("$begintime 00:00:00"), strtotime("$endtime 23:59:59")]];
        if ($begintime)
            $where['a.goods_create_time'] = ['egt', strtotime("$begintime 00:00:00")];
        if ($endtime)
            $where['a.goods_create_time'] = ['elt', strtotime("$endtime 23:59:59")];
        // $data = Goods::alias('a')->field('a.goods_name')->where($where)->select();
        $search = ['type' => $type];
        // 所有商品
        if ($type == 0) {
            return self::alias('a')
                ->field('a.goods_id,a.goods_name,a.goods_create_time,b.goods_category_name,c.goods_main_pic,a.goods_is_delete,a.goods_shelf_state')
                ->join('goods_category b', 'a.goods_category_id=b.goods_category_id', 'left')
                ->join('goods_main_img c', 'a.goods_id=c.goods_id', 'left')
                ->where($where)
                ->where('c.goods_is_main_pic', 1)
                ->where('a.goods_is_delete', 0)
                ->order('a.goods_id', 'desc')
                ->paginate($pagesize)->appends($search);
        }

        // 已上架
        if ($type == 1) {
            return self::alias('a')
                ->field('a.goods_id,a.goods_name,a.goods_create_time,b.goods_category_name,c.goods_main_pic,a.goods_is_delete,a.goods_shelf_state')
                ->join('goods_category b', 'a.goods_category_id=b.goods_category_id', 'left')
                ->join('goods_main_img c', 'a.goods_id=c.goods_id', 'left')
                ->where($where)
                ->where('c.goods_is_main_pic', 1)
                ->where('a.goods_shelf_state', 2)
                ->where('a.goods_is_delete', 0)
                ->order('a.goods_id', 'desc')
                ->paginate($pagesize)->appends($search);
        }
        //已保存商品
        if ($type == 2) {
            return self::alias('a')
                ->field('a.goods_id,a.goods_name,a.goods_create_time,b.goods_category_name,c.goods_main_pic,a.goods_is_delete,a.goods_shelf_state')
                ->join('goods_category b', 'a.goods_category_id=b.goods_category_id', 'left')
                ->join('goods_main_img c', 'a.goods_id=c.goods_id', 'left')
                ->where($where)
                ->where('c.goods_is_main_pic', 1)
                ->where('a.goods_shelf_state', 1)
                ->where('a.goods_is_delete', 0)
                ->order('a.goods_id', 'desc')
                ->paginate($pagesize)->appends($search);
        }
        //下架的商品
        if ($type == 3) {
            return self::alias('a')->field('a.goods_id,a.goods_name,a.goods_create_time,b.goods_category_name,c.goods_main_pic,a.goods_is_delete,a.goods_shelf_state')
                ->join('goods_category b', 'a.goods_category_id=b.goods_category_id', 'left')
                ->join('goods_main_img c', 'a.goods_id=c.goods_id', 'left')
                ->where('a.goods_merchant_id', session('merchant.merchant_id'))
                ->where('c.goods_is_main_pic', 1)
                ->where('goods_shelf_state', 3)
                ->where('a.goods_is_delete', 0)
                ->order('a.goods_id', 'desc')
                ->paginate($pagesize)->appends($search);
        }
    }

    public static function makeFileName()
    {
        $merchantId = session('merchant.merchant_id');
        $store = db('store')->field('store_id')->where('store_merchant_id', $merchantId)->find();
        $storeId = $store['store_id'];
        // 店铺编号+商户编号+时间戳+随机4位数
        $filename = $storeId . $merchantId . time() . mt_rand(1000, 9999);

        return $filename;
    }

    public static function upload($whereName, $filename)
    {
        $uploaddir = config('oss_img_path') . $whereName . '/';
        $name = $_FILES['file']['name'];
        $type = strtolower(substr(strrchr($name, '.'), 1));
        //获取文件类型
        //if (!is_dir($uploaddir)) {
        //    mkdir($uploaddir);
        //}
        $typeArr = array("jpg", "png", "gif");
        if (!in_array($type, $typeArr)) {
            return returnJson(0, '请上传jpg,png或gif类型的图片！');
        }

        $oss = new OSSUtils();
        $res = $oss->uploadFile($uploaddir.$filename . '.' . $type,$_FILES['file']['tmp_name']);
        $res = json_decode($res,true);
        if($res['status'] == 1){
            return $type;
        }else{
            return false;
        }

        //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $filename . '.' . $type)) {
        //    return $type;
        //} else {
        //    return false;
        //}
    }


    //panduan
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }


    public static function getCategory($catId)
    {
        $catData = db('goods_category')->field('goods_category_id,goods_category_name')->find($catId);
        return $catData;
    }


    // 商品修改可变属性
    public static function getVarAttr($goods_id)
    {
        $where = [
            'goods_id' => $goods_id,
            'key' => '颜色'
        ];

        $where2 = [
            'goods_id' => $goods_id,
            'key' => '规格'
        ];
        $data['color'] = db('content_var_attr_content')->where($where)->select();
        $data['guige'] = db('content_var_attr_content')->where($where2)->select();
        return $data;
    }


    // 商品修改商品共有属性
    public static function getSameAttr($goods_id)
    {
        $data = db('goods_attr_content')->where('goods_id', $goods_id)->select();
        return $data;
    }


    // 商品修改商品sku图片
    public static function getSku($goods_id)
    {
        $data = db('goods_sku')->field('a.*,key')
            ->alias('a')
            ->join('content_var_attr_content b', 'a.goods_sku_attr_id=b.content_id', 'left')
            ->where('a.goods_id', $goods_id)->select();
        return $data;
    }

    // 商品修改商品sku图片
    public static function getGoodsMarketRate($act_id)
    {
        $data = db('zj_activity')->field('market_rate,start_time,end_time,status')
            ->where('id',$act_id)->find();
        return $data;
    }

    //商品租赁清单
    public static function getrentlist($goods_id)
    {
        $imgRootPath = config('oss_imgRootPath');
        $data = db('goods_rentlist')->where('goods_id', $goods_id)->select();
        $datacount = count($data);
        for ($i = 0; $i < $datacount; $i++) {

            $data[$i]['imgURL'] = $imgRootPath . 'goods/rentlist/' . $data[$i]['goods_rentlist_img'];

        }

        return $data;
    }


    // 商品主图
    public static function getMainImg($goods_id)
    {
        $data = db('goods_main_img')->where('goods_id', $goods_id)->select();
        return $data;
    }

    // 获取运费模板
    public static function getmobant($goods_id, $mobantype)
    {
        $where = [
            'goods_id' => $goods_id,
            'goods_shipping_tpl_type' => $mobantype,
        ];
        $data = db('goods_shipping_tpl')->where($where)->find();
        return $data;
    }

    // 获取自提点
    public static function getmobantname($goods_id, $mobantype)
    {
        $where = [
            'goods_id' => $goods_id,
            'goods_shipping_tpl_type' => $mobantype,
        ];
        $data = db('goods_shipping_tpl')->field('goods_shipping_tpl_selected')->where($where)->select();

        $count = count($data);
        $arrs = [];
        for ($i = 0; $i < $count; $i++) {
            $arrs[$i] = $data[$i]['goods_shipping_tpl_selected'];
        }

        //$arr=explode(',',$data['goods_shipping_tpl_selected']);
        return $arrs;
    }

    // 商品修改商品租用周期
    public static function getRentPeriod($goods_id)
    {
        $data['data'] = db('rent_period')->where('rent_period_goods_id', $goods_id)->select();
        $data['rent_period_type'] = [];
        foreach ($data['data'] as $k => $v) {
            $data['rent_period_type'][] = $v['rent_period_type'];
        }
        // 租用周期类型去重
        $data['rent_period_type'] = array_unique($data['rent_period_type']);
        // 将数组键初始化从零开始
        $data['rent_period_type'] = array_values($data['rent_period_type']);
        return $data;
    }

    //获取商品周期
    public static function getrent_period_type($goods_id)
    {
        $data = db('rent_period')->field('distinct rent_period_type')->where('rent_period_goods_id', $goods_id)->select();
        $result = [];
        foreach ($data as $v) {
            $rent_period_type = $v['rent_period_type'];
            $result[] = $rent_period_type;
        }

        return $result;
    }

    public static function getrent_period_types($goods_id)
    {
        $data = db('rent_period')
            ->field(
                'rent_period_type,rent_period_min_rent,rent_period_max_rent,rent_period_old_rent_price,
                rent_period_now_rent_price,rent_period_min_advance,rent_period_max_advance','relet_discount'
            )->where('rent_period_goods_id', $goods_id)->select();

        return $data;
    }

    public static function getImgGoodsDetails($goods_id)
    {
        $data = db('goods_details')->where('goods_details_id', $goods_id)->find();
        return $data;
    }

    public static function getRentType($Rentdatestr){
        $typeid = 0;
        switch ($Rentdatestr){
            case "日":
                $typeid = 1;
                break;
            case "周":
                $typeid = 2;
                break;
            case "月":
                $typeid = 3;
                break;
            case "季":
                $typeid = 4;
                break;
            case "年":
                $typeid = 5;
                break;
            default:
                break;
        }
        return $typeid;
    }


    public static function insertData($data)
    {
        try {

            // 运费模板类型：1-快递模板 2-上门模板 3-自提点'
            $express_id = input('param.express_id');
            $todoor = input('param.todoor');
            $since_id = input('param.since_id/a');

            $data['goods_is_free_shipping'] = $data['goods_is_door'] = $data['goods_is_since'] = 2;
            if ($express_id){
                $data['goods_is_free_shipping'] = 1; // 包邮（是）
            }
            if ($todoor){
                $data['goods_is_door'] = 1; // 上门（是）
            }
            if ($since_id){
                $data['goods_is_since'] = 1; // 自提（是）
            }
            $data['wap_show']=0;
            $goods_id = db('goods')->insertGetId($data);

            if ($goods_id) {
                if ($since_id)
                    Goods::insertShippingTpls(3, $goods_id, $since_id);

                if ($todoor)
                    Goods::insertShippingTpl(2, $goods_id, $todoor);
                if ($express_id)
                    Goods::insertShippingTpl(1, $goods_id, $express_id);
            }

            /* ----------商品颜色规格属性处理 商品可变属性-------- */
            $typedata = input('param.rent_type_list');
            $typedata = json_decode($typedata,true);
            $rent_data = [];
            $goods_attr_data = [];
            $attr_data = [];
            /**
             * 商品颜色规格信息存在，则开始预处理
             * $attr_data 属性信息数
             * $goods_attr_data 商品属性信息数组
             * $rent_data 商品对于不同类型的租用条件属性数组
            */
            if( !empty($typedata) ){
                foreach($typedata as $tkey => $tvalue){
                    //添加颜色属性
                    if(!empty($tvalue['color'])){
                        $attr_data[] = array(
                            //'key' => 'color',
                            'key' => '颜色',
                            'value' => $tvalue['color'],
                            'goods_id' => $goods_id,
                        );
                    }
                    foreach($tvalue['children'] as $gk => $gv){
                        //添加规格信息
                        if($tkey == 0){
                            if(!empty($gv['size'])) {
                                $attr_data[] = array(
                                    //'key' => 'size',
                                    'key' => '规格',
                                    'value' => $gv['size'],
                                    'goods_id' => $goods_id,
                                );
                            }
                        }
                        //预生成商品属性信息
                        $goods_attr_data[] = array(
                            'color' => $tvalue['color'],
                            'size' => $gv['size'],
                            'goods_deposit' => $gv['deposit'],
                            'market_price' => $gv['price'],
                            'goods_id' => $goods_id,
                        );
                        foreach($gv['children'] as $rk => $rv){
                                //预处理租用条件信息
                                if(!empty( $rv['time'] )) {
                                    // 续租折扣
                                    $relet_discount = 100;
                                    if (isset($rv['children']['relet_discount'])
                                        && (int)$rv['children']['relet_discount'] > 0
                                        && (int)$rv['children']['relet_discount'] <= 100
                                    ) {
                                        $relet_discount = (int)$rv['children']['relet_discount'];
                                    }
                                    $rent_data[] = array(
                                        'attr_field'=>array($tvalue['color'],$gv['size']),
                                        'rent_period_type' => self::getRentType($rv['time']),
                                        'rent_period_min_rent' => $rv['children']['min_rent'],
                                        'rent_period_max_rent' => ($rv['children']['max_rent'] == 0 ? (-1) : $rv['children']['max_rent']),
                                        'rent_period_old_rent_price' => $rv['children']['oldprice'],
                                        'rent_period_now_rent_price' => $rv['children']['currentprice'],
                                        'rent_period_min_advance' => $rv['children']['min_advance'],
                                        'rent_period_max_advance' => $rv['children']['max_advance'] * 30,
                                        'rent_period_goods_id' => $goods_id,
                                        'rent_period_create_time' => time(),
                                    	'relet_discount'=> $relet_discount
                                    );
                                }
                        }
                    }
                }
                Db::name('content_var_attr_content')->insertAll($attr_data,true);
                //根据颜色和规格处理商品公有信息
                foreach($goods_attr_data as $k => $v){
                    $where = [
                        'value' => $v['color'],
                        'goods_id' => $goods_id,
                        'key' => '颜色',
                    ];
                    $color_id = Db::name('content_var_attr_content')->field('content_id')->where($where)->find();
                    $color_id = $color_id['content_id'];
                    $where['value']=$v['size'];
                    $where['key']='规格';
                    $size_id = Db::name('content_var_attr_content')->field('content_id')->where($where)->find();
                    $size_id = $size_id['content_id'];
                    if(!empty($color_id) &&!empty($size_id)){
                        $goods_attr_data[$k]['content_var_attr_id'] = $color_id.",".$size_id;
                    }else{
                        $goods_attr_data[$k]['content_var_attr_id'] = $color_id."".$size_id;
                    }
                    unset($goods_attr_data[$k]['color'],$goods_attr_data[$k]['size']);
                }
                Db::name('goods_attr_content')->insertAll($goods_attr_data,true);
                $goods_attr_content_array = db('goods_attr_content')->field('content_id,content_var_attr_id')->where('goods_id', $goods_id)->select();
                //由颜色和规格添加租用信息中的相关公有属性
                foreach($rent_data as $k=>$v) {
                    foreach ($goods_attr_content_array as $ck => $cv) {
                        if(!empty($cv['content_var_attr_id'])){
                            $area_str = db("content_var_attr_content")->field("value,key")->where("content_id in ({$cv['content_var_attr_id']})")->select();
                        }
                        if (!empty($area_str)) {
                            if (count($area_str) == 2) {
                                foreach ($area_str as $a => $b) {
                                    if ($b['key'] == "颜色" && $b['value'] == $v['attr_field'][0]) {
                                        if ($area_str[1 - $a]['value'] == $v['attr_field'][1] && $area_str[1 - $a]['key'] == "规格") {
                                            $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                            break;
                                        }
                                    }
                                }
                            } else {
                                if ($area_str[0]['key'] == "颜色" && $area_str[0]['value'] == $v['attr_field'][0]) {
                                    $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                    break;
                                } else {
                                    if ($area_str[0]['key'] == "规格" && $area_str[0]['value'] == $v['attr_field'][1]) {
                                        $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                        break;
                                    }
                                }
                            }
                        }else{
                            $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                            break;
                        }
                    }
                    unset($rent_data[$k]['attr_field']);
                }
                Db::name('rent_period')->insertAll($rent_data,true);
            }

            /*---------------------spart line-------------------*/

            // 商品sku属性及图片入库
            $goods_sku_img = input('param.goods_sku_img/a');
            $goods_sku_attr_value = input('param.goods_sku_attr_value/a');

            $my_goods_id = $goods_id;

            if ($goods_sku_img) {
                $goods_sku_imgCount = count($goods_sku_img);
                $goods_sku_attr_value = array_filter($goods_sku_attr_value);
                foreach ($goods_sku_img as $k => $v) {
                    $where = [
                        'value' => $goods_sku_attr_value[$k],
                        'goods_id' => $my_goods_id,
                    ];
                    $attrs = db('content_var_attr_content')
                        ->field('content_id')
                        ->where($where)
                        ->find();

                    $data = [
                        'goods_sku_img' => $v,
                        'goods_id' => $my_goods_id,
                        'goods_sku_attr_name' => '',
                        'goods_sku_attr_id' => $attrs['content_id'],
                        'goods_sku_attr_value' => $goods_sku_attr_value[$k]
                    ];

                    Db::name('goods_sku')->insert($data);

                }
            }
            // 商品主图入库
            /*            $goodsMain = input('param.file_mains');

                        $mains_images = explode("|", $goodsMain);
                        $new_mains_images = array_values(array_filter($mains_images));
                        if (!empty($new_mains_images)) {
                            $goodsMainCount = count($new_mains_images);
                            foreach ($new_mains_images as $k => $v) {
                                if ($k == 0) {
                                    $data = [
                                        'goods_main_pic' => $v,
                                        'goods_id' => $goods_id,
                                        'goods_is_main_pic' => 1
                                    ];

                                    Db::name('goods_main_img')->insert($data);
                                } else {
                                    $data = [
                                        'goods_main_pic' => $v,
                                        'goods_id' => $goods_id,
                                        'goods_is_main_pic' => 2
                                    ];
                                    Db::name('goods_main_img')->insert($data);
                                }
                            }
                        }*/
            $mainImgs = input('file_mains/a');
            $mainImgs = explode(',', $mainImgs[0]);
            foreach ($mainImgs as $k => $v) {
                if ($k == 0) {
                    $mainImgArr = [
                        'goods_main_pic' => $v,
                        'goods_id' => $goods_id,
                        'goods_is_main_pic' => 1
                    ];
                } else {
                    $mainImgArr = [
                        'goods_main_pic' => $v,
                        'goods_id' => $goods_id,
                        'goods_is_main_pic' => 2
                    ];
                }
                Db::name('goods_main_img')->insert($mainImgArr);
            }
            //商品租赁清单入库
/*            $rentlist = input('param.goods_rentlist_img/a');
            $rentlist_name = input('param.goods_rentlist_name/a');
            if ($rentlist && $rentlist_name) {
                $rentlistImg = array_filter($rentlist);
                $goods_rentlist_name = array_filter($rentlist_name);
                foreach ($rentlistImg as $k => $v) {

                    $data = [
                        'goods_id' => $goods_id,
                        'goods_rentlist_img' => $v,
                        'goods_rentlist_name' => isset($goods_rentlist_name[$k]) ? $goods_rentlist_name[$k] : '',
                    ];

                    Db::name('goods_rentlist')->insert($data);
                }
            }*/
            $rentImgs = input('file_rents');
            $rentImgs = json_decode($rentImgs, true);
            foreach ($rentImgs['data'] as $k => $v) {
                $rentImgArr = [
                    'goods_id' => $goods_id,
                    'goods_rentlist_img' => $v['imgsrc'],
                    'goods_rentlist_name' => $v['title']
                ];
                Db::name('goods_rentlist')->insert($rentImgArr);
            }
        } catch (Exception $e) {
            //print $e->getMessage();
            exit();
        }

    }

    public static function updateData($data)
    {
        $goods_id = $data['goods_id'];

            $goods_id = $data['goods_id'];
            unset($data['goods_id']);

            // 运费模板类型：1-快递模板 2-上门模板 3-自提点'
            $express_id = (int)input('param.express_id');
            $todoor = (int)input('param.todoor');
            $since_id = input('param.since_id/a');


            $data['goods_is_free_shipping'] = $data['goods_is_door'] = $data['goods_is_since'] = 2;// 默认否
            if ($express_id){
                $data['goods_is_free_shipping'] = 1; // 包邮（是）
            }
            if ($todoor){
                $data['goods_is_door'] = 1; // 上门（是）
            }
            if ($since_id){
                $data['goods_is_since'] = 1; // 自提（是）
            }
            $data['wap_show']=0;
            $up_res = db('goods')->where("goods_id = $goods_id")->update($data);
            if ($goods_id) {

                if ($since_id) {
                    $goodsShippingTpls = db('goods_shipping_tpl')->where(['goods_shipping_tpl_type' => 3,'goods_id' => $goods_id])->field('goods_shipping_tpl_selected')->select();
                    if (!$goodsShippingTpls) {
                        Goods::insertShippingTpls(3, $goods_id, $since_id);
                    } else {
                        $tpls = [];
                        foreach ($goodsShippingTpls as $goodsShippingTpl) {
                            $tpls[] = $goodsShippingTpl['goods_shipping_tpl_selected'];
                        }
                        $same = [];
                        foreach ($tpls as $tpl) {
                            if (in_array($tpl,$since_id)) {
                                $same[] = $tpl;

                            } else {
                                db('goods_shipping_tpl')->where(['goods_shipping_tpl_type' => 3,'goods_id' => $goods_id,'goods_shipping_tpl_selected' => $tpl])->delete();
                            }
                        }

                        foreach ($since_id as $sinceId_value){
                            if (!in_array($sinceId_value,$same)) {
                                Goods::insertShippingTpls(3, $goods_id, [$sinceId_value]);
                            }
                        }
                    }
                } else 
				{
                    db('goods_shipping_tpl')->where(['goods_shipping_tpl_type' => 3,'goods_id' => $goods_id])->delete();
                }

//                if ($todoor)
//				{
					$tplId = db('goods_shipping_tpl')->where(['goods_shipping_tpl_type' => 2,'goods_id' => $goods_id])->value('goods_shipping_tpl_id');
					if($tplId)
					{
						db('goods_shipping_tpl')->where(['goods_shipping_tpl_id' =>$tplId])->update(['goods_shipping_tpl_selected'=>$todoor]);
					}else
					{
						 Goods::insertShippingTpl(2, $goods_id, $todoor);
					}
					
                   
					
				//}
                if ($express_id)
				{
					$tplId = db('goods_shipping_tpl')->where(['goods_shipping_tpl_type' => 1,'goods_id' => $goods_id])->value('goods_shipping_tpl_id');
					if($tplId)
					{
						db('goods_shipping_tpl')->where(['goods_shipping_tpl_id' =>$tplId])->update(['goods_shipping_tpl_selected'=>$express_id]);
					}else
					{
						Goods::insertShippingTpl(1, $goods_id, $express_id);
					}
					 
                    
					
				}
            }

            /* ----------商品颜色规格属性处理 商品可变属性-------- */
            $typedata = input('param.rent_type_list');
            $typedata = json_decode($typedata,true);
            $rent_data = [];
            $goods_attr_data = [];
            $attr_data = [];
            /**
             * 商品颜色规格信息存在，则开始预处理
             * $attr_data 属性信息数
             * $goods_attr_data 商品属性信息数组
             * $rent_data 商品对于不同类型的租用条件属性数组
             */
            if( !empty($typedata) ){
                foreach($typedata as $tkey => $tvalue){
                    //添加颜色属性
                    if(!empty($tvalue['color'])){
                        $attr_data[] = array(
                            //'key' => 'color',
                            'key' => '颜色',
                            'value' => $tvalue['color'],
                            'goods_id' => $goods_id,
                        );
                    }
                    foreach($tvalue['children'] as $gk => $gv){
                        //添加规格信息
                        if($tkey == 0){
                            if(!empty($gv['size'])) {
                                $attr_data[] = array(
                                    //'key' => 'size',
                                    'key' => '规格',
                                    'value' => $gv['size'],
                                    'goods_id' => $goods_id,
                                );
                            }
                        }
                        //预生成商品属性信息
                        $goods_attr_data[] = array(
                            'color' => $tvalue['color'],
                            'size' => $gv['size'],
                            'goods_deposit' => $gv['deposit'],
                            'market_price' => $gv['price'],
                            'goods_id' => $goods_id,
                        );
                        foreach($gv['children'] as $rk => $rv){
                            //预处理租用条件信息
                            if(!empty( $rv['time'] )) {
                                // 续租折扣
                                $relet_discount = 100;
                                if (isset($rv['children']['relet_discount'])
                                    && (int)$rv['children']['relet_discount'] > 0
                                    && (int)$rv['children']['relet_discount'] <= 100
                                ) {
                                    $relet_discount = (int)$rv['children']['relet_discount'];
                                }

                                $rent_data[] = array(
                                    'attr_field'=>array($tvalue['color'],$gv['size']),
                                    'rent_period_type' => self::getRentType($rv['time']),
                                    'rent_period_min_rent' => $rv['children']['min_rent'],
                                    'rent_period_max_rent' => ($rv['children']['max_rent'] == 0 ? (-1) : $rv['children']['max_rent']),
                                    'rent_period_old_rent_price' => $rv['children']['oldprice'],
                                    'rent_period_now_rent_price' => $rv['children']['currentprice'],
                                    'rent_period_min_advance' => $rv['children']['min_advance'],
                                    'rent_period_max_advance' => $rv['children']['max_advance'] * 30,
                                    'rent_period_goods_id' => $goods_id,
                                    'rent_period_create_time' => time(),
                                    'relet_discount'=> $relet_discount
                                );
                            }
                        }
                    }
                }
                $is_delete = Db::name('content_var_attr_content')->where("goods_id",$goods_id)->delete();
                if($is_delete !== false){
                    Db::name('content_var_attr_content')->insertAll($attr_data,true);
                }
                //根据颜色和规格处理商品公有信息
                foreach($goods_attr_data as $k => $v){
                    $where = [
                        'goods_id' => $goods_id,
                        'value' => $v['color'],
                        'key' => '颜色',
                    ];
                    $color_id = Db::name('content_var_attr_content')->field('content_id')->where($where)->find();
                    $color_id = $color_id['content_id'];
                    $where['value']=$v['size'];
                    $where['key']='规格';
                    $size_id = Db::name('content_var_attr_content')->field('content_id')->where($where)->find();
                    $size_id = $size_id['content_id'];
                    if(!empty($color_id) &&!empty($size_id)){
                        $goods_attr_data[$k]['content_var_attr_id'] = $color_id.",".$size_id;
                    }else{
                        $goods_attr_data[$k]['content_var_attr_id'] = $color_id."".$size_id;
                    }
                    unset($goods_attr_data[$k]['color'],$goods_attr_data[$k]['size']);
                }
                $is_delete = Db::name('goods_attr_content')->where("goods_id",$goods_id)->delete();
                if($is_delete !== false){
                    Db::name('goods_attr_content')->insertAll($goods_attr_data,true);
                }

                $goods_attr_content_array = db('goods_attr_content')->field('content_id,content_var_attr_id')->where('goods_id', $goods_id)->select();
                //由颜色和规格添加租用信息中的相关公有属性
                foreach($rent_data as $k=>$v) {
                    foreach ($goods_attr_content_array as $ck => $cv) {
                        if(!empty($cv['content_var_attr_id'])){
                            $area_str = db("content_var_attr_content")->field("value,key")->where("content_id in ({$cv['content_var_attr_id']})")->select();
                        }
                        if (!empty($area_str)) {
                            if (count($area_str) == 2) {
                                foreach ($area_str as $a => $b) {
                                    if ($b['key'] == "颜色" && $b['value'] == $v['attr_field'][0]) {
                                        if ($area_str[1 - $a]['value'] == $v['attr_field'][1] && $area_str[1 - $a]['key'] == "规格") {
                                            $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                            break;
                                        }
                                    }
                                }
                            } else {
                                if ($area_str[0]['key'] == "颜色" && $area_str[0]['value'] == $v['attr_field'][0]) {
                                    $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                    break;
                                } else {
                                    if ($area_str[0]['key'] == "规格" && $area_str[0]['value'] == $v['attr_field'][1]) {
                                        $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                                        break;
                                    }
                                }
                            }
                        }else{
                            $rent_data[$k]['rent_period_goods_attr_id'] = $cv['content_id'];
                            break;
                        }
                    }
                    unset($rent_data[$k]['attr_field']);
                }
                $is_delete = Db::name('rent_period')->where("rent_period_goods_id",$goods_id)->delete();
                if($is_delete !== false){
                    Db::name('rent_period')->insertAll($rent_data,true);
                }
                //Db::name('rent_period')->insertAll($rent_data,true);
            }

            /*---------------------spart line-------------------*/

            // 商品sku属性及图片入库
            $goods_sku_img = input('param.goods_sku_img/a');
            $goods_sku_attr_value = input('param.goods_sku_attr_value/a');

            $my_goods_id = $goods_id;

            if ($goods_sku_img) {
                $goods_sku_imgCount = count($goods_sku_img);
                $goods_sku_attr_value = array_filter($goods_sku_attr_value);
                $skudata = [];
                foreach ($goods_sku_img as $k => $v) {
                    $where = [
                        'value' => $goods_sku_attr_value[$k],
                        'goods_id' => $my_goods_id,
                    ];
                    $attrs = db('content_var_attr_content')
                        ->field('content_id')
                        ->where($where)
                        ->find();

                    $skudata[] = [
                        'goods_sku_img' => $v,
                        'goods_id' => $my_goods_id,
                        'goods_sku_attr_name' => '',
                        'goods_sku_attr_id' => $attrs['content_id'],
                        'goods_sku_attr_value' => $goods_sku_attr_value[$k]
                    ];
                    //Db::name('goods_sku')->insert($data);
                }
                $is_delete = Db::name('goods_sku')->where("goods_id",$goods_id)->delete();
                if($is_delete !== false){
                    Db::name('goods_sku')->insertAll($skudata);
                }
            }
            // 商品主图入库
            /*            $goodsMain = input('param.file_mains');

                        $mains_images = explode("|", $goodsMain);
                        $new_mains_images = array_values(array_filter($mains_images));
                        if (!empty($new_mains_images)) {
                            $goodsMainCount = count($new_mains_images);
                            foreach ($new_mains_images as $k => $v) {
                                if ($k == 0) {
                                    $data = [
                                        'goods_main_pic' => $v,
                                        'goods_id' => $goods_id,
                                        'goods_is_main_pic' => 1
                                    ];

                                    Db::name('goods_main_img')->insert($data);
                                } else {
                                    $data = [
                                        'goods_main_pic' => $v,
                                        'goods_id' => $goods_id,
                                        'goods_is_main_pic' => 2
                                    ];
                                    Db::name('goods_main_img')->insert($data);
                                }
                            }
                        }*/
            $mainImgs = input('file_mains/a');
            $mainImgs = explode(',', $mainImgs[0]);
            $mainImgArr = [];
            foreach ($mainImgs as $k => $v) {
                if ($k == 0) {
                    $mainImgArr[] = [
                        'goods_main_pic' => $v,
                        'goods_id' => $goods_id,
                        'goods_is_main_pic' => 1
                    ];
                } else {
                    $mainImgArr[] = [
                        'goods_main_pic' => $v,
                        'goods_id' => $goods_id,
                        'goods_is_main_pic' => 2
                    ];
                }
                //Db::name('goods_main_img')->insert($mainImgArr);
            }
            $is_delete = Db::name('goods_main_img')->where("goods_id",$goods_id)->delete();
            if($is_delete !== false){
                Db::name('goods_main_img')->insertAll($mainImgArr);
            }
            //商品租赁清单入库
            /*            $rentlist = input('param.goods_rentlist_img/a');
                        $rentlist_name = input('param.goods_rentlist_name/a');
                        if ($rentlist && $rentlist_name) {
                            $rentlistImg = array_filter($rentlist);
                            $goods_rentlist_name = array_filter($rentlist_name);
                            foreach ($rentlistImg as $k => $v) {

                                $data = [
                                    'goods_id' => $goods_id,
                                    'goods_rentlist_img' => $v,
                                    'goods_rentlist_name' => isset($goods_rentlist_name[$k]) ? $goods_rentlist_name[$k] : '',
                                ];

                                Db::name('goods_rentlist')->insert($data);
                            }
                        }*/
            $rentImgs = input('file_rents');
            $rentImgs = json_decode($rentImgs, true);
            $rentImgArr = [];
            foreach ($rentImgs['data'] as $k => $v) {
                $rentImgArr[] = [
                    'goods_id' => $goods_id,
                    'goods_rentlist_img' => $v['imgsrc'],
                    'goods_rentlist_name' => $v['title']
                ];
                //Db::name('goods_rentlist')->insert($rentImgArr);
            }
            $is_delete = Db::name('goods_rentlist')->where("goods_id",$goods_id)->delete();
            if($is_delete !== false){
                Db::name('goods_rentlist')->insertAll($rentImgArr,true);
            }
       // } catch (Exception $e) {
            //print $e->getMessage();
           // exit();
       // }

    }


}

  





 
